package com.api.custom.assets.formmode;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;

import com.customization.commons.LogTool;
import weaver.conn.RecordSet;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.soa.workflow.request.Cell;
import weaver.soa.workflow.request.DetailTable;
import weaver.soa.workflow.request.DetailTableInfo;
import weaver.soa.workflow.request.MainTableInfo;
import weaver.soa.workflow.request.Property;
import weaver.soa.workflow.request.RequestInfo;
import weaver.soa.workflow.request.RequestService;
import weaver.soa.workflow.request.Row;
import weaver.workflow.workflow.WorkflowVersion;

import com.alibaba.fastjson.JSONObject;
import com.customization.assets.util.DBTools;
import com.customization.assets.util.DateTools;
import com.engine.common.util.ParamUtil;

/**
 * @author	Huangwm
 * @description	实物资产管理-部门借用列表快捷发起归还或续借
 */
@Path("/assets/formmode")
public class CreateRequestByBorrowList {

	private LogTool log = new LogTool("/log/assetlog/huangwm/CreateRequestByBorrowList",false);
	private static DBTools dbTools = new DBTools();
	private static DateTools dateTools = new DateTools();
	
	@POST
	@Path("/createRequestByBorrowList")
	@Produces(MediaType.APPLICATION_JSON)
	public Map<String, Object> createRequestByBorrowList(@Context HttpServletRequest request,@Context HttpServletResponse response){
		Map<String, Object> apiResult = new HashMap<String, Object>();
		String requestid = "";
		try {
			Map<String, Object> requestParams = ParamUtil.request2Map(request);
			String ids = "";
			if(requestParams.containsKey("ids")){
				ids = requestParams.get("ids").toString();
				if(ids.equals("")){
					apiResult.put("status", false);
					apiResult.put("msg", "参数ids无值,请检查查询页代码块");
					return apiResult;
				}
			}else{
				apiResult.put("status", false);
				apiResult.put("msg", "缺少参数ids,请检查查询页代码块");
				return apiResult;
			}
			String type = "";
			if(requestParams.containsKey("type")){
				type = requestParams.get("type").toString();
				if(type.equals("")){
					apiResult.put("status", false);
					apiResult.put("msg", "参数type无值,无法区分归还还是续借,请检查查询页代码块");
					return apiResult;
				}		
			}else{
				apiResult.put("status", false);
				apiResult.put("msg", "缺少参数type,请检查查询页代码块");
				return apiResult;
			}
			
			HttpSession session = request.getSession();
			User user = (User) session.getAttribute("weaver_user@bean");
			String userid = user.getUID()+"";
			log.writeLog("通过部门借用记录查询列表快捷发起流程 本地归还所关联的借用记录id为："+ids+";发起人id为："+userid);
			
			List<Map<String, String>> assetsBorrowListInfo = getAssetsBorrowListInfo(ids);
			Map<String, String> mainMap = new HashMap<String, String>();
			RequestService service = new RequestService();
			if(type.equals("reBack")){
				requestid = service.createRequest(setRequestInfo_gh(userid, ids,mainMap, assetsBorrowListInfo));
				apiResult.put("status", true);
				apiResult.put("msg", "流程创建成功");
			}else if(type.equals("continue")){
				String cDate = "";
				if(!requestParams.containsKey("cDate")){
					apiResult.put("status", false);
					apiResult.put("msg", "续借动作缺少参数cDate,请检查查询页代码块");
					return apiResult;
				}else{
					cDate = requestParams.get("cDate").toString();
					if(type.equals("")){
						apiResult.put("status", false);
						apiResult.put("msg", "续借动作参数cDate无值,请检查查询页代码块");
						return apiResult;
					}
				}
				requestid = service.createRequest(setRequestInfo_xj(userid, ids,mainMap, assetsBorrowListInfo,cDate));
				apiResult.put("status", true);
				apiResult.put("msg", "流程创建成功");
			}
			apiResult.put("requestid", requestid);
		} catch (Exception e) {
			apiResult.put("status", false);
			apiResult.put("requestid",requestid);
			apiResult.put("errorCode", "-999");
			apiResult.put("msg", "程序异常 "+e.getMessage());
			e.printStackTrace();
		}
		log.writeLog("结果："+JSONObject.toJSONString(apiResult));
		return apiResult;
	}
	
	/**
	 * 根据id集合获取本次的设备借用信息
	 * @param ids
	 * @return
	 */
	public  List<Map<String, String>> getAssetsBorrowListInfo(String ids) throws SQLException{
		List<Map<String, String>> list = new ArrayList<Map<String, String>>();
		RecordSet rs = new RecordSet();
		String sql = "select * from uf_swzcjyjl where id in("+ids+")";
		log.writeLog("本次设备借用信息查询sql->>>"+sql);
		rs.execute(sql);
		while(rs.next()){
			Map<String, String> data = new HashMap<String, String>();
			data.put("jyzcbh", Util.null2String(rs.getString("jyzcbh")));
			data.put("zcbh", Util.null2String(rs.getString("zcbh")));
			data.put("lx", Util.null2String(rs.getString("lx")));
			data.put("pp", Util.null2String(rs.getString("pp")));
			data.put("ggxh", Util.null2String(rs.getString("ggxh")));
			data.put("jyr", Util.null2String(rs.getString("jyr")));
			data.put("szks", Util.null2String(rs.getString("szks")));
			data.put("szcs", Util.null2String(rs.getString("szcs")));
			data.put("jyqx", Util.null2String(rs.getString("jyqx")));
			data.put("jyyy", Util.null2String(rs.getString("jyyy")));
			data.put("jylc", Util.null2String(rs.getString("jylc")));
			data.put("mxid", Util.null2String(rs.getString("mxid")));
			list.add(data);
			log.writeLog(data.toString());
		}
		log.writeLog("本次设备借用信息查询结束");
		return list;
	}
	
	/**
	 * 获取资产名称
	 * @param ids
	 * @return
	 */
	public  String getAssetsName(String ids){
		RecordSet rs = new RecordSet();
		String assetsName = "";
		String sql = "select zcmc from uf_swzczmxx where id in(select jyzcbh from uf_swzcjyjl where id in("+ids+"))";
		rs.execute(sql);
		if(rs.next()){
			assetsName = Util.null2String(rs.getString("zcmc"));
		}
		return assetsName;
	}
	
	/**
	 * 设置归还流程流转信息
	 * @param userid
	 * @param mainMap
	 * @param detaMaps
	 * @return
	 */
	public RequestInfo setRequestInfo_gh(String userid,String ids,Map<String, String> mainMap,List<Map<String, String>> detaMaps) throws Exception{
		RequestInfo requestInfo = new RequestInfo();
		String activeWFID = WorkflowVersion.getActiveVersionWFID("122");
		log.writeLog("获取到的活动版本workflowid  "+activeWFID);
		requestInfo.setWorkflowid(activeWFID);
		requestInfo.setIsNextFlow("1");
		requestInfo.setCreatorid(userid);
		requestInfo.setDescription(dbTools.getSubName(userid)+" "+dbTools.getLastname(userid)+" 关于["+getAssetsName(ids)+"]等设备归还申请");
		requestInfo.setMainTableInfo(setMainTableInfo_gh(userid, mainMap));
		requestInfo.setDetailTableInfo(setDetailTable_gh(detaMaps));
		return requestInfo;
	}
	
	/**
	 * 设置续借流程流转信息
	 * @param userid
	 * @param mainMap
	 * @param detaMaps
	 * @return
	 */
	public RequestInfo setRequestInfo_xj(String userid,String ids,Map<String, String> mainMap,List<Map<String, String>> detaMaps,String cDate) throws Exception{
		RequestInfo requestInfo = new RequestInfo();
		String activeWFID = WorkflowVersion.getActiveVersionWFID("125");
		log.writeLog("获取到的活动版本workflowid  "+activeWFID);
		requestInfo.setWorkflowid(activeWFID);
		requestInfo.setIsNextFlow("1");
		requestInfo.setCreatorid(userid);
		requestInfo.setDescription(dbTools.getSubName(userid)+" "+dbTools.getLastname(userid)+" 关于["+getAssetsName(ids)+"]等设备续借申请");
		requestInfo.setMainTableInfo(setMainTableInfo_xj(userid, mainMap));
		requestInfo.setDetailTableInfo(setDetailTable_xj(detaMaps,cDate));
		return requestInfo;
	}
	
	/**
	 * 设置主表字段
	 * @param fieldName
	 * @param fieldValue
	 * @return
	 */
	public Property setMainField(String fieldName,String fieldValue){
		Property field = new Property();
		field.setName(fieldName);
		field.setValue(fieldValue);
		return field;
	}
 
	/**
	 * 设置明细表字段
	 * @param fieldName
	 * @param fieldValue
	 * @return
	 */
	public Cell setDetailField(String fieldName,String fieldValue){
		Cell field = new Cell();
		field.setName(fieldName);
		field.setValue(fieldValue);
		return field;
	}
	
	/**
	 * 设置归还流程主表数据
	 * @param userid
	 * @param params
	 * @return
	 */
	public MainTableInfo setMainTableInfo_gh(String userid,Map<String, String> params){
		log.writeLog("开始设置归还流程主表信息 当前用户id："+userid);
		MainTableInfo mainTableInfo = new MainTableInfo();
		mainTableInfo.addProperty(setMainField("sqr", userid));
		mainTableInfo.addProperty(setMainField("sqrq",dateTools.getCurrentDate()));
		mainTableInfo.addProperty(setMainField("szks", dbTools.getDepid(userid)));
		mainTableInfo.addProperty(setMainField("szcs", dbTools.getSubid(userid)));
		mainTableInfo.addProperty(setMainField("sfygh", "2"));//是否已归还默认为规划你确认中
		log.writeLog("归还流程主表设置完成");
		return mainTableInfo;
	}
	
	/**
	 * 设置续借流程主表数据
	 * @param userid
	 * @param params
	 * @return
	 */
	public  MainTableInfo setMainTableInfo_xj(String userid,Map<String, String> params){
		log.writeLog("开始设置续借流程主表信息 当前用户id："+userid);
		MainTableInfo mainTableInfo = new MainTableInfo();
		mainTableInfo.addProperty(setMainField("sqr", userid));
		mainTableInfo.addProperty(setMainField("sqrq",dateTools.getCurrentDate()));
		mainTableInfo.addProperty(setMainField("szks", dbTools.getDepid(userid)));
		mainTableInfo.addProperty(setMainField("szcs", dbTools.getSubid(userid)));
		mainTableInfo.addProperty(setMainField("sfygh", "0"));
		log.writeLog("续借流程主表设置完成");
		return mainTableInfo;
	}
	
	/**
	 * 设置归还流程明细表数据
	 * @param detailList
	 * @return
	 */
	public DetailTable setDetailTableInfo_gh(List<Map<String, String>> detailList){
		log.writeLog("开始设置归还流程明细表1");
		DetailTable detailTable = new DetailTable();
		detailTable.setId("1");
		if(detailList.size()>0){
			for (Map<String, String> map : detailList) {
				Row row = new Row();
				row.addCell(setDetailField("ghsb", Util.null2String(map.get("jyzcbh"))));
				row.addCell(setDetailField("sbbh", Util.null2String(map.get("zcbh"))));
				row.addCell(setDetailField("lx", Util.null2String(map.get("lx"))));
				row.addCell(setDetailField("pp", Util.null2String(map.get("pp"))));
				row.addCell(setDetailField("ggxh", Util.null2String(map.get("ggxh"))));
				row.addCell(setDetailField("jyr", Util.null2String(map.get("jyr"))));
				row.addCell(setDetailField("szks", Util.null2String(map.get("szks"))));
				row.addCell(setDetailField("szcs", Util.null2String(map.get("szcs"))));
				row.addCell(setDetailField("jyqx", Util.null2String(map.get("jyqx"))));
				row.addCell(setDetailField("jyyy", Util.null2String(map.get("jyyy"))));
				row.addCell(setDetailField("sbzt", "0"));
				row.addCell(setDetailField("jylc", Util.null2String(map.get("jylc"))));
				row.addCell(setDetailField("jylcmxid", Util.null2String(map.get("mxid"))));
				detailTable.addRow(row);
			}
		}	
		return detailTable;
	}
	
	/**
	 * 设置续借流程明细表数据
	 * @param detailList
	 * @return
	 */
	public DetailTable setDetailTableInfo_xj(List<Map<String, String>> detailList,String cDate){
		log.writeLog("开始设置续借流程明细表1");
		DetailTable detailTable = new DetailTable();
		detailTable.setId("1");
		if(detailList.size()>0){
			for (Map<String, String> map : detailList) {
				Row row = new Row();
				row.addCell(setDetailField("ghsb", Util.null2String(map.get("jyzcbh"))));
				row.addCell(setDetailField("sbbh", Util.null2String(map.get("zcbh"))));
				row.addCell(setDetailField("lx", Util.null2String(map.get("lx"))));
				row.addCell(setDetailField("pp", Util.null2String(map.get("pp"))));
				row.addCell(setDetailField("ggxh", Util.null2String(map.get("ggxh"))));
				row.addCell(setDetailField("jyr", Util.null2String(map.get("jyr"))));
				row.addCell(setDetailField("szks", Util.null2String(map.get("szks"))));
				row.addCell(setDetailField("szcs", Util.null2String(map.get("szcs"))));
				row.addCell(setDetailField("jyqx", Util.null2String(map.get("jyqx"))));
				row.addCell(setDetailField("xjqx", cDate));
				row.addCell(setDetailField("jylc", Util.null2String(map.get("jylc"))));
				row.addCell(setDetailField("jylcmxid", Util.null2String(map.get("mxid"))));
				detailTable.addRow(row);
			}
		}	
		return detailTable;
	}
	
	/**
	 * 添加归还流程明细数据到明细表
	 * @param detailList
	 * @return
	 */
	public  DetailTableInfo setDetailTable_gh(List<Map<String, String>> detailList){
		DetailTableInfo detailTableInfo = new DetailTableInfo();
		if(detailList.size()>0){
			detailTableInfo.setDetailTable(new DetailTable[]{
				setDetailTableInfo_gh(detailList)
			});
		}
		log.writeLog("归还流程明细表1设置完成");
		return detailTableInfo;
	}
	
	/**
	 * 添加续借流程明细数据到明细表
	 * @param detailList
	 * @return
	 */
	public DetailTableInfo setDetailTable_xj(List<Map<String, String>> detailList,String cDate){
		DetailTableInfo detailTableInfo = new DetailTableInfo();
		if(detailList.size()>0){
			detailTableInfo.setDetailTable(new DetailTable[]{
				setDetailTableInfo_xj(detailList,cDate)
			});
		}
		log.writeLog("续借流程明细表1设置完成");
		return detailTableInfo;
	}
}
